package com.example.mqtt;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class MqttClient {
    private static final String BROKER_URL = "tcp://192.168.3.234:1883";
    private static final String CLIENT_ID = "JavaClient";
    private static final String TOPIC = "test/topic";
    private static final int QOS = 1;

    public static void main(String[] args) {
        try {
            // 创建MQTT客户端
            MemoryPersistence persistence = new MemoryPersistence();
            MqttAsyncClient client = new MqttAsyncClient(BROKER_URL, CLIENT_ID, persistence);
            
            // 设置回调函数
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    System.out.println("连接丢失: " + cause.getMessage());
                }

                @Override
                public void messageArrived(String topic, MqttMessage message) {
                    String payload = new String(message.getPayload(), StandardCharsets.UTF_8);
                    System.out.println("\n收到消息:");
                    System.out.println("  主题: " + topic);
                    System.out.println("  内容: " + payload);
                    System.out.println("  QoS: " + message.getQos());
                    System.out.print("\n请输入要发送的消息（输入'exit'退出）: ");
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    System.out.println("消息发送完成");
                }
            });
            
            // 连接设置
            MqttConnectOptions connectOptions = new MqttConnectOptions();
            connectOptions.setCleanSession(true);
            
            // 连接服务器
            System.out.println("正在连接到MQTT服务器: " + BROKER_URL);
            client.connect(connectOptions).waitForCompletion();
            System.out.println("已连接到MQTT服务器");
            
            // 订阅主题
            client.subscribe(TOPIC, QOS).waitForCompletion();
            System.out.println("已订阅主题: " + TOPIC);
            
            // 发送消息
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入要发送的消息，输入'exit'退出：");
            
            String input;
            while (!(input = scanner.nextLine()).equals("exit")) {
                MqttMessage message = new MqttMessage(input.getBytes(StandardCharsets.UTF_8));
                message.setQos(QOS);
                
                client.publish(TOPIC, message).waitForCompletion();
                System.out.println("已发送消息: " + input);
                System.out.print("请输入要发送的消息（输入'exit'退出）: ");
            }
            
            // 断开连接
            client.disconnect().waitForCompletion();
            System.out.println("已断开与MQTT服务器的连接");
            
            scanner.close();
        } catch (MqttException e) {
            System.out.println("MQTT错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
} 